package com.tarim.streetdance.service.impl;

import com.tarim.streetdance.mapper.VideoLikeMapper;
import com.tarim.streetdance.model.Video;
import com.tarim.streetdance.model.VideoLike;
import com.tarim.streetdance.service.VideoLikeService;
import com.tarim.streetdance.service.VideoService;
import com.tarim.streetdance.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class VideoLikeServiceImpl implements VideoLikeService {
    @Autowired
    private VideoLikeMapper videoLikeMapper;
    @Autowired
    private VideoService videoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertSelective(VideoLike record) {
        record.setDr(0);
        record.setCreateTime(new Date());
        Long viewLike = this.selectCountByVideoId(record);
        Video video = new Video();
        video.setId(record.getVideoId());
        video.setLikenum(viewLike + 1);
        videoService.updateForAddLikenum(video);
        return videoLikeMapper.insertSelective(record);
    }

    @Override
    public int updateForDelete(VideoLike record) {
        int num = videoLikeMapper.updateForDelete(record);
        Long likenum = this.selectCountByVideoId(record);
        Video video = new Video();
        video.setId(record.getVideoId());
        video.setLikenum(likenum);
        videoService.updateForAddLikenum(video);
        return num;
    }

    @Override
    public PageBean<VideoLike> selectByUserId(PageBean<VideoLike> pageBean, VideoLike record) {
        record.addExtField("pageIndex", pageBean.getPageIndex());
        record.addExtField("pageSize", pageBean.getPageSize());
        List<VideoLike> list = videoLikeMapper.selectByUserId(record);
        Long count = videoLikeMapper.selectByUserIdCount(record);
        pageBean.setTotalCount(count);
        pageBean.setData(list.toArray());
        return pageBean;
    }

    @Override
    public Long selectCountByVideoId(VideoLike record) {
        return videoLikeMapper.selectCountByVideoId(record);
    }

    @Override
    public boolean selectCountForIsLike(VideoLike record) {
        Long count = videoLikeMapper.selectCountForIsLike(record);
        if (count != 0) {
            return true;
        }
        return false;
    }
}